import logging
import pymysql
from django.http import JsonResponse, HttpResponse
from comment.comservice import add_filter
from comment.comviews import com_views, success_response, err_response, format_response
from utils.dbutils import PymysqlUtil, DB_Config, MysqlTools
from utils.formatutils import get_params
from utils.pageutils import paging_simple
from .sqlmap import *
from utils.jpushutils import *
from functools import reduce
from utils.rbmqutils import RabbitPublisher

mysql_tools = MysqlTools(db_config=DB_Config.get("default"))

def all_task_classify(params):
    """
    查询所有任务分类
    :param params:
    :return:
    """
    dict = {
        "user_id": "user_id"
    }
    params = get_params(params, dict)
    if isinstance(params, JsonResponse):
        return params
    sql = TaskSqlMap.FIND_ALL_CLASSIFY.format(**params)
    result_all = mysql_tools.select_all(sql)
    return success_response(result_all)


def mytasks(params):  # 查询所有
    dict = {
        "user_id": "user_id"
    }
    page_params = {
        "isall": "isAll",
        "size": "limit",
        "page": "page",
        "query_str":"query_str",
        "status_id": "status_id",
        "priority_level": "priority_level"
    }
    params = get_params(params, dict, page_params)
    if isinstance(params, JsonResponse):
        return params
    # if not params["user_id"]:
    #     return err_response(210)
    my_name = mysql_tools.select_one(TaskSqlMap.FIND_NAME.format(**params))
    params["my_name"] = my_name.get("user_name")
    sql = add_filter(TaskSqlMap.MYTASK_LIST, params, ["query_str", "status_id", "priority_level"], **TaskSqlMap.FILTER_PARAMS)
    sql += " order by t.publish_time desc"
    result = mysql_tools.select_all(sql.format(**params))
    if not result:
        return success_response([])
    if isinstance(result, JsonResponse):
        return result
    if params.get("isall") != 1:
        result = paging_simple(result, params.get("page"), params.get("size"))
    for res in result:
        res["star_time"] = str(res["star_time"])
        res["end_time"] = str(res["end_time"])
        res["progress_speed"] = res.get("progress_speed") * 100
        if res["priority_level"] == 0:
            res["priority_level_name"] = "低"
        elif res["priority_level"] == 1:
            res["priority_level_name"] = "中"
        else:
            res["priority_level_name"] = "高"
    return success_response(result)


def task_add(params):  # 添加
    dict = {
        "title": "title",
        "task_describe": "task_describe",
        "star_time": "star_time",
        "end_time": "end_time",
        "reciverlist_id": "reciverlist_id", # 执行人可以有多个,str用;分割
        "implement_id": "implement_id",     # 负责人
        "task_push_user_id": "task_push_user_id"
    }
    null_params = {
        "task_project_id": "task_project_id",
        "attach_id": "attach_id"
    }
    params = get_params(params, dict, null_params)
    if isinstance(params, JsonResponse):
        return params
    # for key, val in params.items():
    #     if key in ["attach_id", "task_project_id"]:
    #         continue
    #     if val is None:
    #         return err_response(210)
    if not params.get("attach_id"):
        params["attach_id"] = "null"
    if not params.get("task_project_id"):
        params["task_project_id"] = "null"
    if isinstance(params.get("reciverlist_id"), list):
        return err_response(210, "reciverlist_id的类型是str,用;分割")
    list_reciverlist_id = []
    for chr in params.get("reciverlist_id").split(";"):
        list_reciverlist_id.append(int(chr))
    params["reciverlist_id"] = list_reciverlist_id
    params["reciverlist"] = ""
    params["reciverlist_user"] = ""
    for reciver in params.get("reciverlist_id"):
        reciverlist = mysql_tools.select_one(TaskSqlMap.FIND_NAME.format(**{"user_id": reciver}))
        params["reciverlist"] += reciverlist.get("real_name") + ";"
        params["reciverlist_user"] += reciverlist.get("user_name") + ";"
    params["reciverlist"] = params.get("reciverlist")[0:-1]
    params["reciverlist_user"] = params.get("reciverlist_user")[0:-1]
    implement = mysql_tools.select_one(TaskSqlMap.FIND_NAME.format(**{"user_id": params.get("implement_id")}))
    params["implement"] = implement.get("real_name")
    params["implement_user"] = implement.get("user_name")
    status_id = mysql_tools.select_one(TaskSqlMap.FIND_STATUS_ID.format(**{"status_name": "未开始"}))
    params["status_id"] = status_id["status_id"]
    sql = TaskSqlMap.TASK_ADD.format(**params)
    mysql_tools.execute_sql(sql)
    task_id = mysql_tools.select_one(TaskSqlMap.GET_ID).get("id")
    for user in params.get("reciverlist_id"):
        sql = TaskSqlMap.TASK_USER_ADD.format(
            **{"status_id": params["status_id"], "task_id": task_id, "task_recive_user_id": user})
        mysql_tools.execute_sql(sql)
    list_user = params.get("reciverlist_user").split(";")
    if params.get("implement_user") not in list_user:
        list_user.append(params.get("implement_user"))
    # push_dict = {
    #     "message": "你收到一个新任务",
    #     "push_user": list_user
    # }
    # RabbitPublisher.run("queue_name", push_dict)
    return success_response({"task_id": task_id})


def subordinates_task(params):
    dict = {
        "user_id": "user_id"
    }
    page_params = {
        "isall": "isAll",
        "size": "limit",
        "page": "page",
        "query_str":"query_str",
        "priority_level": "priority_level",
        "status_id": "status_id"
    }
    params = get_params(params, dict, page_params)
    if isinstance(params, JsonResponse):
        return params
    sql = TaskSqlMap.FIND_NAME.format(**params)
    user_result = mysql_tools.select_one(sql, msg="user_id is error")
    if isinstance(user_result,JsonResponse):
        return user_result
    if user_result is None:
        return err_response(404)
    role_id = user_result.get("role_value")
    params["my_role_id"] = role_id
    result = []
    run_function = lambda x, y: x if y in x else x + [y]
    if role_id <= 1:
        ALL_OTHER = mysql_tools.select_all(TaskSqlMap.GET_ALL_OTHER.format(**params))
        if not ALL_OTHER:
            return success_response([])
        for user_name in ALL_OTHER:
            params["user_name"] = user_name.get("user_name")
            params["next_user_id"] = user_name.get("next_user_id")
            sql_sub = TaskSqlMap.subordinates_task_all
            sql = add_filter(sql_sub, params, ["query_str", "priority_level", "status_id"], **TaskSqlMap.FILTER_PARAMS)
            sql += " order by t.publish_time desc"
            sql = sql.format(**params)
            fin = mysql_tools.select_all(sql)
            result.extend(fin)
            result = reduce(run_function, [[], ] + result)
    else:
        ALL_DOWN = mysql_tools.select_all(TaskSqlMap.GET_DOWN_ID.format(**params))
        if not ALL_DOWN:
            return success_response([])
        for user_name in ALL_DOWN:
            params["user_name"] = user_name.get("user_name")
            params["next_user_id"] = user_name.get("next_user_id")
            sql_sub = TaskSqlMap.subordinates_task_sub
            sql = add_filter(sql_sub, params, ["query_str", "priority_level", "status_id"], **TaskSqlMap.FILTER_PARAMS)
            sql += " order by t.publish_time desc"
            sql = sql.format(**params)
            fin = mysql_tools.select_all(sql)
            result.extend(fin)
            result = reduce(run_function, [[], ] + result)
    if params.get("isall") != 1:
        result = paging_simple(result, params.get("page"), params.get("size"))
    if not result:
        return success_response([])
    if isinstance(result, JsonResponse):
        return result
    for res in result:
        res["star_time"] = str(res["star_time"])
        res["end_time"] = str(res["end_time"])
        res["progress_speed"] = res["progress_speed"] * 100
        if res["priority_level"] == 0:
            res["priority_level_name"] = "低"
        elif res["priority_level"] == 1:
            res["priority_level_name"] = "中"
        else:
            res["priority_level_name"] = "高"
    return success_response(result)


def task_details(params):
    dict = {
        "task_id": "task_id"
    }
    params = get_params(params, dict)
    if isinstance(params, JsonResponse):
        return params
    # for key, val in params.items():
    #     if not val:
    #         return err_response(210)
    sql = TaskSqlMap.task_details.format(**params)
    sql_comment = TaskSqlMap.task_comment.format(**params)
    result = mysql_tools.select_one(sql)
    if not result:
        return success_response({})
    if isinstance(result, JsonResponse):
        return result
    task_comment = mysql_tools.select_all(sql_comment)
    if task_comment:
        for res in task_comment:
            res["comment_time"] = str(res["comment_time"])
    result["task_comment"] = task_comment
    result["star_time"] = str(result.get("star_time"))
    result["end_time"] = str(result.get("end_time"))
    result["publish_time"] = str(result.get("publish_time"))
    result["progress_speed"] = result.get("progress_speed") * 100
    return success_response(result)


def speed_setting(params):
    dict = {
        "user_id": "user_id",
        "progress_speed": "progress_speed",
        "comment": "comment",
        "task_id": "task_id"
    }
    params = get_params(params, dict)
    if isinstance(params, JsonResponse):
        return params
    # for key, val in params.items():
    #     if val is None:
    #         return err_response(210)
    if params["progress_speed"] > 100 or params["progress_speed"] < 0:
        return err_response(210)
    elif params["progress_speed"] == 100:
        dict_new = {"status_name": "已完成"}
    elif params["progress_speed"] == 0:
        dict_new = {"status_name": "未开始"}
    else:
        dict_new = {"status_name": "进行中"}
    sql_status_id = TaskSqlMap.FIND_STATUS_ID.format(**dict_new)
    status_id = mysql_tools.select_one(sql_status_id)
    params["status_id"] = status_id["status_id"]
    params["progress_speed"] = params["progress_speed"] / 100
    sql = TaskSqlMap.speed_setting.format(**params)
    sql_insert_comment = TaskSqlMap.insert_comment.format(**params)
    mysql_tools.execute_sql(sql)
    mysql_tools.execute_sql(sql_insert_comment,commit=True)
    return success_response()


def speed_info(params):
    dict = {
        "task_id": "task_id"
    }
    page_params = {
        "isall": "isAll",
        "size": "limit",
        "page": "page"
    }
    params = get_params(params, dict, page_params)
    if isinstance(params, JsonResponse):
        return params
    # if not params["task_id"]:
    #     return err_response(210)
    sql = TaskSqlMap.SPEED_INFO.format(**params)
    result = mysql_tools.select_all(sql)
    if params.get("isall") != 1:
        result = paging_simple(result, params.get("page"), params.get("size"))
    if not result:
        return success_response([])
    if isinstance(result,JsonResponse):
        return result
    for res in result:
        res["end_time"] = str(res["end_time"])
        res["progress_speed"] = res["progress_speed"] * 100
    return success_response(result)


@format_response
def index(request):
    return com_views(request, {
        "mytasks": mytasks,
        "task_add": task_add,
        "subordinates_task": subordinates_task,
        "task_details": task_details,
        "speed_setting": speed_setting,
        "speed_info": speed_info,
        "all_task_classify":all_task_classify
    })
